package com.boarsoft.config.core;

import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.Properties;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 
 * @author Mac_J
 *
 */
public class SystemPropsListener implements ConfigFileListener {
	private static final Logger log = LoggerFactory.getLogger(SystemPropsListener.class);

	/** 相对于当前应用实例运行目录的配置文件存储目录路径 */
	protected String absoluteDir = "";
	/** 相对于当前应用实例运行目录的配置文件存储目录路径 */
	protected String relativeDir = "";
	/** */
	protected String regex = "(.*)(\\.properties)$";
	/** */
	protected String charset = StandardCharsets.UTF_8.name();

	/** */
	protected FileFilter fileFilter = new FileFilter() {
		@Override
		public boolean accept(File f) {
			return f.getName().matches(regex);
		}
	};

	public SystemPropsListener() {
		absoluteDir = this.getClass().getClassLoader()//
				.getResource(".").getFile().concat(relativeDir);
	}

	@Override
	public boolean onReady(String frp) {
		if (!frp.endsWith(".properties")) {
			return false;
		}
		String ap = this.getAbosultePath(frp);
		Properties p = new Properties();
		try {
			p.load(new InputStreamReader(new FileInputStream(new File(ap)), charset));
			System.getProperties().putAll(p);
			return true;
		} catch (IOException e) {
			log.error("Error on read config file {}", ap, e);
		}
		return false;
	}

	@Override
	public boolean onRemove(String frp) {
		// Nothing to do
		return false;
	}

	@Override
	public String getAbosoluteDir() {
		return absoluteDir;
	}

	@Override
	public String getAbosultePath(String rp) {
		return new StringBuilder(absoluteDir)//
				.append(relativeDir).append(rp).toString();
	}

	@Override
	public String getAbosultePath() {
		return absoluteDir.concat(relativeDir);
	}

	@Override
	public String getRelativeDir() {
		return relativeDir;
	}

	public void setRelativeDir(String relativeDir) {
		this.relativeDir = relativeDir;
	}

	public String getRegex() {
		return regex;
	}

	public void setRegex(String regex) {
		this.regex = regex;
	}

	public FileFilter getFileFilter() {
		return fileFilter;
	}

	public void setFileFilter(FileFilter fileFilter) {
		this.fileFilter = fileFilter;
	}

	public String getCharset() {
		return charset;
	}

	public void setCharset(String charset) {
		this.charset = charset;
	}

}